package CellEngine;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.*;
import java.net.*;

public class ServerPort extends Thread
{
	public final int port;
	private int maxPlayers;
	private String password = null;
	private boolean active = false;
	public ArrayList<ServerClientSocket> connections;
    public HashMap<Integer,ServerClientSocket> connectionMap;
    
	public ServerPort(int port)
	{
		if(port > 65535 || port < 1)
		{
			port = -1;
        	throw new IllegalArgumentException();
		}
		this.port = port;
	}
	
	public void start()
	{
		active = true;
		connections = new ArrayList<ServerClientSocket>();
		if(port == -1)
		{
			throw new IllegalThreadStateException();
		}

        try
        {
            ServerSocket celld = new ServerSocket(port);
            while(active)
            {
                Socket socket = celld.accept();
                int clientID = getFreeSlot();
                if(clientID >= 0)
                {
                	ServerClientSocket client = new ServerClientSocket(socket, clientID);
                	connections.add(client);
                	connectionMap.put(client.id, client);
                	client.start();
                }
                else
                	socket.close();
            }
        }
        catch(Exception e)
        {
            Server.log.write("Server Port error!\n");
            Server.log.write(e.toString());
        }
		return;
	}
	private int getFreeSlot()
	{
		for(int i = 0; i <= connections.size(); i++)
			if(!connectionMap.containsKey(i))
				return i;
		return -1;
	}
	// This function sets the password which is required to connect to the server
	// Set to null to allow anyone to connect
	public void setPassword(String password)
	{
		this.password = password;
	}
	public String getPasword() { return password; }
	// True if a password is required to connect, otherwise false
	public boolean passwordEnabled()
	{
		if(password == null)
			return false;
		return true;
	}
}
